<template>
  <a-card hoverable class="flex-column login" style="align-items: center;width: 400px;margin: 10% auto">
    <h2 style="text-align: center; margin-bottom: 35px">登录 Final-Gateway</h2>
    <div class="flex-column" style="width: 350px">
      <a-input v-model="form.username" placeholder="请输入账号">
        <template #prepend>
          <icon-user/>
        </template>
      </a-input>
      <a-input style="margin-top: 15px" type="password" v-model="form.password" placeholder="请输入密码">
        <template #prepend>
          <icon-lock/>
        </template>
      </a-input>
      <div class="flex-column" style="width: 100%;margin-top: 15px">
        <div class="flex-row" style="margin-top: -10px;margin-bottom: 10px">
          <div style="flex: 1"></div>
          <a-button type="text" @click="handleClick">忘记密码</a-button>
        </div>
        <a-button :loading="loadding" type="primary" @click="handleSubmit" style="width: 100%">登录账号
        </a-button>
      </div>
    </div>
  </a-card>
  <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel" :hide-cancel="true">
    <template #title>
      提示
    </template>
    <div>账号密码在 <b>conf/config.xml</b> 配置文件中的 admin 标签内</div>
  </a-modal>
</template>
<script setup>
import {IconUser, IconLock} from "@arco-design/web-vue/es/icon";
import {ref, onMounted} from "vue";
import apiAll from "@/api/apiAll.js";
import {Message} from "@arco-design/web-vue";
import Cookies from "js-cookie";
import {useRouter} from "vue-router";
import {useUserStore} from '@/stores/user.js'

const router = useRouter();
const userStore = useUserStore()
const loadding = ref(false);
const form = ref({
  username: "",
  password: "",
});
const visible = ref(false);
const handleOk = () => {
  visible.value = false;
};
const handleCancel = () => {
  visible.value = false;
}
const handleClick = () => {
  visible.value = true;
};

const handleSubmit = () => {
  if (form.value.username !== "") {
    window.localStorage.setItem("username", form.value.username);
  }
  loadding.value = true;
  apiAll.userApi.login(form.value.username, form.value.password)
      .then((res) => {
        userStore.user = res.data
        // window.localStorage.setItem("user", JSON.stringify(res.data));
        Cookies.set("token", res.data);
        Message.success("登录成功");
        setTimeout(() => {
          router.replace({
            path: "/",
          });
        }, 1000);
      })
      .finally(() => {
        setTimeout(() => {
          loadding.value = false;
        }, 500);
      });
};

onMounted(() => {
  const u = window.localStorage.getItem("username");
  if (u) {
    form.value.username = u;
  }
});
</script>
<style scoped>
.login {
  margin-top: 20px;
}
</style>
